import {create} from "zustand";
import {persist} from "zustand/middleware";
import {doLogin} from "@/api";

interface AccessControlStore {
    accessCode: string;
    token: string;
    accessCodeErrorMsg: string;
    updateCode: (_: string) => void;
    updateToken: (_: string) => void;
    isAuthorized: () => boolean;
    goToLogin: () => void;
    doLogin: () => Promise<string>;
}

export const useAccessStore:any = create<AccessControlStore>()(
    persist(
        (set, get) => ({
            accessCode: "",
            token: "",
            accessCodeErrorMsg: "",
            updateCode(code: string) {
                set(() => ({accessCode: code}));
            },
            updateToken(token: string) {
                set(() => ({token}));
            },
            isAuthorized() {
                return !!get().token;
            },
            goToLogin() {
                set(() => ({
                    accessCode: "",
                    token: ""
                }));
            },
            async doLogin() {
                const res = await doLogin();
                const {code, data} = await res.json();
                console.log("data", data);
                // 这里需要根据返回结果设置
                switch (code) {
                    case '0000':
                        console.log("登录成功！");
                        get().updateToken(data);
                        set(() => ({accessCodeErrorMsg: ""}));
                        break;
                    case '0002':
                        set(() => ({accessCodeErrorMsg: "验证码已过期,请获取最新验证码"}));
                        break;
                    case '0003':
                        set(() => ({accessCodeErrorMsg: "验证码不存在,请确认最新验证码"}));
                        break;
                    default:
                        set(() => ({accessCodeErrorMsg: "未知失败"}));
                        break;
                }
                return data;
            }
        }),
        {
            name: 'access-store',
            version: 1
        }
    )
)
